/**
 * ASR语音识别演示应用 JavaScript
 */

class ASRApp {
    constructor() {
        this.ws = null;
        this.isRecording = false;
        this.init();
    }

    init() {
        // 绑定文件选择事件
        const fileInput = document.getElementById('audioFile');
        fileInput.addEventListener('change', this.handleFileSelect.bind(this));
        
        // 初始化状态
        this.updateStatus('未连接', 'disconnected');
    }

    // 文件选择处理
    handleFileSelect(event) {
        const file = event.target.files[0];
        const fileInfo = document.getElementById('fileInfo');
        const fileName = document.getElementById('fileName');
        const fileSize = document.getElementById('fileSize');

        if (file) {
            fileName.textContent = `文件名: ${file.name}`;
            fileSize.textContent = `大小: ${this.formatFileSize(file.size)}`;
            fileInfo.style.display = 'block';
        } else {
            fileInfo.style.display = 'none';
        }
    }

    // 格式化文件大小
    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 上传音频文件
    async uploadAudio() {
        const fileInput = document.getElementById('audioFile');
        const file = fileInput.files[0];
        
        if (!file) {
            this.showNotification('请选择音频文件', 'warning');
            return;
        }

        // 检查文件大小 (50MB限制)
        if (file.size > 50 * 1024 * 1024) {
            this.showNotification('文件大小超过50MB限制', 'error');
            return;
        }

        // 检查文件格式
        const allowedFormats = ['wav', 'mp3', 'm4a', 'flac', 'ogg'];
        const fileExtension = file.name.split('.').pop().toLowerCase();
        if (!allowedFormats.includes(fileExtension)) {
            this.showNotification(`不支持的文件格式: ${fileExtension}`, 'error');
            return;
        }

        this.showLoading(true);
        this.updateResult('正在上传和识别音频文件...');

        try {
            const formData = new FormData();
            formData.append('file', file);

            const response = await fetch('/upload_audio', {
                method: 'POST',
                body: formData
            });

            const data = await response.json();

            if (data.success) {
                this.updateResult(`识别结果: ${data.text}`);
                this.showNotification('音频识别成功', 'success');
            } else {
                this.updateResult(`识别失败: ${data.error}`);
                this.showNotification('音频识别失败', 'error');
            }
        } catch (error) {
            this.updateResult(`上传失败: ${error.message}`);
            this.showNotification('网络错误，请重试', 'error');
        } finally {
            this.showLoading(false);
        }
    }

    // 开始实时识别
    startRealtime() {
        if (this.ws) {
            this.ws.close();
        }

        this.ws = new WebSocket(`ws://${window.location.host}/ws`);
        
        this.ws.onopen = () => {
            this.updateStatus('已连接，正在监听...', 'connected');
            this.updateResult('等待语音输入...');
            this.isRecording = true;
            this.showNotification('实时识别已启动', 'success');
        };

        this.ws.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data);
                if (data.type === 'asr_result') {
                    this.updateResult(`实时识别: ${data.text}`);
                }
            } catch (error) {
                console.error('解析WebSocket消息失败:', error);
            }
        };

        this.ws.onclose = () => {
            this.updateStatus('连接已断开', 'disconnected');
            this.isRecording = false;
        };

        this.ws.onerror = (error) => {
            this.updateStatus('连接错误', 'error');
            this.showNotification('WebSocket连接失败', 'error');
            console.error('WebSocket error:', error);
        };
    }

    // 停止实时识别
    stopRealtime() {
        if (this.ws) {
            this.ws.close();
            this.ws = null;
        }
        this.updateStatus('已停止', 'disconnected');
        this.isRecording = false;
        this.showNotification('实时识别已停止', 'success');
    }

    // 更新状态显示
    updateStatus(message, type) {
        const statusElement = document.getElementById('status');
        const statusDot = document.getElementById('statusDot');
        
        statusElement.textContent = `状态: ${message}`;
        
        // 移除所有状态类
        statusDot.className = 'status-dot';
        
        // 添加对应的状态类
        if (type === 'connected') {
            statusDot.classList.add('connected');
        } else if (type === 'error') {
            statusDot.classList.add('error');
        }
    }

    // 更新识别结果
    updateResult(text) {
        const resultElement = document.getElementById('result');
        resultElement.textContent = text;
    }

    // 清空结果
    clearResult() {
        this.updateResult('等待识别结果...');
        this.showNotification('结果已清空', 'success');
    }

    // 复制结果
    copyResult() {
        const resultElement = document.getElementById('result');
        const text = resultElement.textContent;
        
        if (text && text !== '等待识别结果...') {
            navigator.clipboard.writeText(text).then(() => {
                this.showNotification('结果已复制到剪贴板', 'success');
            }).catch(() => {
                // 降级方案
                const textArea = document.createElement('textarea');
                textArea.value = text;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                this.showNotification('结果已复制到剪贴板', 'success');
            });
        } else {
            this.showNotification('没有可复制的内容', 'warning');
        }
    }

    // 显示/隐藏加载状态
    showLoading(show) {
        const loadingOverlay = document.getElementById('loadingOverlay');
        loadingOverlay.style.display = show ? 'flex' : 'none';
    }

    // 显示通知
    showNotification(message, type = 'info') {
        const notification = document.getElementById('notification');
        const notificationText = document.getElementById('notificationText');
        
        notificationText.textContent = message;
        notification.className = `notification ${type}`;
        notification.style.display = 'flex';
        
        // 3秒后自动隐藏
        setTimeout(() => {
            this.hideNotification();
        }, 3000);
    }

    // 隐藏通知
    hideNotification() {
        const notification = document.getElementById('notification');
        notification.style.display = 'none';
    }
}

// 全局函数，供HTML调用
let app;

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    app = new ASRApp();
});

// 全局函数
function uploadAudio() {
    app.uploadAudio();
}

function startRealtime() {
    app.startRealtime();
}

function stopRealtime() {
    app.stopRealtime();
}

function clearResult() {
    app.clearResult();
}

function copyResult() {
    app.copyResult();
}

function hideNotification() {
    app.hideNotification();
}
